package com.example.zhengjiyu

import android.os.Bundle
import android.view.*
import android.widget.EditText
import android.widget.Button
import android.widget.Toast
import androidx.fragment.app.Fragment
import java.io.FileOutputStream

class AddWordFragment : Fragment() {

    private lateinit var editTextWord: EditText
    private lateinit var addWordButton: Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_add_word, container, false)
        editTextWord = view.findViewById(R.id.editTextWord)
        addWordButton = view.findViewById(R.id.addWordButton)

        addWordButton.setOnClickListener {
            val newWord = editTextWord.text.toString().trim()
            if (newWord.isNotEmpty()) {
                saveWordToFile(newWord)
                Toast.makeText(context, "单词已添加", Toast.LENGTH_SHORT).show()
                editTextWord.text.clear() // 清空输入框
            } else {
                Toast.makeText(context, "请输入单词", Toast.LENGTH_SHORT).show()
            }
        }
        return view
    }

    // 保存单词到文件
    private fun saveWordToFile(word: String) {
        try {
            val fileOutputStream: FileOutputStream = requireContext().openFileOutput("words.txt", android.content.Context.MODE_APPEND)
            fileOutputStream.write((word + "\n").toByteArray())
            fileOutputStream.close()
        } catch (e: Exception) {
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show()
        }
    }
}
